<template>
  <el-dialog
    class="close-dialog"
    :title="dialog.title"
    width="1000px"
    :close-on-click-modal="false"
    :visible.sync="dialog.visible"
    v-if="dialog.visible"
  >
    <div class="main">
      <div class="type2-title margin-t0">案件基本信息</div>
      <div class="row">
        <devformVue label="案件名称 " classname="w2">
          {{ showData.caseName }}
        </devformVue>
        <devformVue label="案件编号" classname="w2">
          {{ showData.caseNo }}
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="收案时间" classname="w2">
          {{ showData.receiptDate }}
        </devformVue>
        <devformVue label="案件类型 " classname="w2">
          {{ showData.categoryName }}
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="客户"> {{ showData.customerName }} </devformVue>
      </div>
      <div class="row">
        <!-- <devformVue label="委托人" classname="w2">
          {{ showData.agent }}
        </devformVue> -->
        <devformVue label="对方当事人" classname="w2">
          {{ showData.targetPartyName }}
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="合同金额(元) " classname="w2">
          {{ showData.fixedCosts }}
        </devformVue>
        <devformVue label="收费方式" classname="w2">
          <dict-tag
            :options="dict.type.payment_type"
            :value="showData.paymentType"
          />
          <!-- 固定收费 -->
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="受理机构"> {{ showData.acceptOrgName }} </devformVue>
      </div>
      <el-form
        label-width="120px"
        :model="formline"
        class="dev-form"
        :rules="rules"
        ref="formline"
      >
        <el-form-item label="收款总额" class="w3" prop="totalAmount" inline>
          <el-input-number
            v-model="formline.totalAmount"
            :precision="2"
            :step="0.1"
            :min="Number(total)"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="已开票金额"
          class="w3"
          prop="invoicedAmount"
          inline
        >
          <el-input-number
            v-model="formline.invoicedAmount"
            :precision="2"
            :step="0.1"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="未开票金额"
          prop="uninvoicedAmount"
          inline
          class="w3"
        >
          {{ uninvoicedAmount }}
        </el-form-item>
        <template v-if="showData.status == 3">
          <el-form-item label="是否退款" class="w3" prop="refund" inline>
            <el-radio-group v-model="formline.refund">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="退款总额"
            prop="invoicedAmount"
            class="w7"
            inline
          >
            <el-input-number
              v-model="formline.refundAmount"
              :precision="2"
              :step="0.1"
              :min="0"
            ></el-input-number>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="分配信息" prop="c">
            收入总额: {{ formline.totalAmount }} 已分配总额：{{
              total
            }}
            已分配比例：{{ showproportion }}%
          </el-form-item>
          <el-form-item label="律师分配" prop="c">
            <div
              class="row mar-10"
              v-for="(item, index) of formline.lawyers"
              :key="index + 'lawyers'"
            >
              <div class="col w3">
                <span>律师人员：</span>
                {{ formline.lawyers[index].personName }}
              </div>

              <div class="col w3">
                <span>分配比例：</span>

                <el-input-number
                  v-model="formline.lawyers[index].percentage"
                  @change="onpercentage(index, 'lawyers')"
                  :precision="2"
                  :step="0.1"
                  :max="1"
                  :min="0"
                ></el-input-number>
              </div>
              <div class="col w3" style="width: 250px">
                <span>分配金额:</span
                ><span style="width: 200px; text-align: left">{{
                  formline.lawyers[index].amount
                }}</span>
              </div>
            </div>
            <el-button @click="onaddlawyers">增加</el-button>
          </el-form-item>
          <el-form-item label="其他费用分配" prop="c">
            <div
              class="row mar-10"
              v-for="(item, index) of formline.others"
              :key="index + 'others'"
            >
              <div class="col w3">
                <span style="width: 180px">费用说明：</span>
                <el-input
                  v-model="formline.others[index].description"
                  placeholder="请输入费用说明"
                >
                </el-input>
              </div>

              <div class="col w3">
                <span>分配比例：</span>
                <el-input-number
                  v-model="formline.others[index].percentage"
                  @change="onpercentage(index, 'others')"
                  :precision="2"
                  :step="0.1"
                  :max="1"
                  :min="0"
                ></el-input-number>
              </div>
              <div class="col w3" style="width: 250px">
                <span>分配金额:</span
                ><span style="width: 200px; text-align: left">{{
                  formline.others[index].amount
                }}</span>
              </div>
            </div>
            <el-button @click="onadd('others', 1)">增加</el-button>
          </el-form-item>
          <el-form-item label="公摊成本信息" prop="c">
            <div
              class="row mar-10"
              v-for="(item, index) of formline.shared"
              :key="index + 'shared'"
            >
              <div class="col w5">
                <span style="width: 180px">公摊成本说明：</span>
                <el-input
                  v-model="formline.shared[index].description"
                  placeholder="请输入公摊成本说明"
                >
                </el-input>
              </div>

              <div class="col w5">
                <span>成本金额：</span>
                <el-input-number
                  v-model="formline.shared[index].amount"
                  @change="onpercentage(index, 'shared')"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                ></el-input-number>
              </div>
            </div>
            <el-button @click="onadd('shared', 2)">增加</el-button>
          </el-form-item>
        </template>
      </el-form>
    </div>
    <div class="foot">
      <el-button @click="submit" type="primary">确定</el-button>
      <el-button @click="cancle">取消</el-button>
    </div>
    <userModal ref="userModal" @submit="userSubmit" />
  </el-dialog>
</template>

<script>
import devformVue from "./devform.vue";
import Decimal from "decimal.js";
import userModal from "../customer/userModal.vue";
import { casefinancial, purgecase, getfinance } from "@/api/case/case";
export default {
  components: { devformVue, userModal },
  dicts: ["subCategory_id", "payment_type"],
  data() {
    return {
      dialog: {
        visible: false,
        title: "财务信息（结案） ",
      },
      showData: {},
      formline: {
        caseId: "",
        totalAmount: "",
        invoicedAmount: "",
        lawyers: [],
        others: [],
        shared: [],
        refundAmount: "",
        refund: "",
      },
      rules: {
        refund: [
          { required: true, message: "请选择是否退款", trigger: "change" },
        ],
        invoicedAmount: [
          { required: true, message: "请输入退款总额", trigger: "change" },
        ],
      },
      proportion: "", //已分配比例
      options2: [],
      arr1: [], //律师分配
    };
  },
  computed: {
    uninvoicedAmount() {
      //未开票金额
      return Decimal(this.formline.totalAmount || 0).sub(
        Decimal(this.formline.invoicedAmount || 0).toFixed(
          2,
          Decimal.ROUND_HALF_UP
        )
      );
    },
    showproportion() {
      return Decimal(this.proportion || 0)
        .mul(Decimal(100))
        .toFixed(2, Decimal.ROUND_HALF_UP);
    },
    total() {
      //已分配总额=收款总额*已分配比例

      return Decimal(this.formline.totalAmount || 0)
        .mul(Decimal(this.proportion || 0))
        .toFixed(2, Decimal.ROUND_HALF_UP);
    },
  },
  watch: {
    "formline.totalAmount"(val, oldval) {
      //总金额变化，表格的比例金额变化
      let sum = this.countSum();
      console.log("变化", val, oldval, sum);
      if (sum > 1) {
        this.formline.totalAmount = oldval;

        this.$set(this.formline, "totalAmount", oldval);
        this.$message.error("收款总额不能小于已分配金额!");
        return;
      } else {
        this.proportion = sum;
      }
      let lawyers = this.formline.lawyers.map((item, index) => {
        console.log(item);
        item.amount = Decimal(val)
          .mul(Decimal(item.percentage))
          .toFixed(2, Decimal.ROUND_HALF_UP);
      });
      let others = this.formline.others.map((item, index) => {
        item.amount = Decimal(val)
          .mul(Decimal(item.percentage))
          .toFixed(2, Decimal.ROUND_HALF_UP);
      });
      console.log(lawyers, others);
      // this.$set(this.formline, "shared", shared);
      // this.$set(this.formline, "lawyers", lawyers);
      // this.$set(this.formline, "others", others);
    },
  },
  methods: {
    price(val) {
      val = val.match(/^\d*(\.?\d{0,2})/g)[0] || null;
      // if (isNaN(val)) {
      //   val = "";
      // }
      // //格式化去掉却没有输入小数位的小数点
      // val = +val;
      console.log(val);
    },
    onpercentage(index, name) {
      //比例变化计算，name数组，index下表，sum比例总和

      let sum = this.countSum();
      if (sum > 1) {
        if (name == "shared") {
          this.$set(this.formline.shared[index], "amount", "");
        } else {
          this.$set(this.formline[name][index], "percentage", "");
        }

        // this.formline[name][index].percentage=''
        this.$message.error("分配比例超过收入总额，请重新输入!");
      } else {
        this.proportion = sum; //已分配比例
        if (name != "shared") {
          let amount = Decimal(this.formline.totalAmount)
            .mul(Decimal(this.formline[name][index].percentage))
            .toFixed(2, Decimal.ROUND_HALF_UP);
          this.$set(this.formline[name][index], "amount", amount); //分配金额
        }
      }
    },
    userSubmit(val) {
      console.log(val);
      let data = {
        allocType: 0,
        amount: "",
        amount: "",
        percentage: "",
        remark: "",
        personName: val.userName,
      };
      this.formline.lawyers.push({ ...val, ...data });
    },
    //计算比例
    countSum() {
      let sum1 = this.formline.lawyers.reduce((pre, cur) => {
        console.log(cur, pre);
        return Decimal(pre)
          .add(Decimal(cur.percentage))
          .toFixed(2, Decimal.ROUND_HALF_UP);
      }, 0);

      let sum2 = this.formline.others.reduce((pre, cur) => {
        console.log(cur, pre);
        return Decimal(pre)
          .add(Decimal(cur.percentage))
          .toFixed(2, Decimal.ROUND_HALF_UP);
      }, 0);
      let sum3 = this.formline.shared.reduce((pre, cur) => {
        //公摊费用转换成比例
        return Decimal(pre)
          .add(Decimal(cur.amount).div(Decimal(this.formline.totalAmount)))
          .toFixed(4, Decimal.ROUND_HALF_UP);
      }, 0);

      let sum = Decimal(sum1)
        .add(Decimal(sum2))
        .add(Decimal(sum3))
        .toFixed(4, Decimal.ROUND_HALF_UP);
      return sum;
    },
    //打开弹窗
    async open(row) {
      console.log(row, "---------------");
      this.showData = { ...row };
      this.$data.formline = this.$options.data().formline;
      this.formline.caseId = row.id;
      let res = await getfinance(row.id);
      this.formline = res.data;
      this.dialog.title =
        row.status == 2
          ? `${row.caseName}-财务信息(结案)`
          : `${row.caseName}-财务信息(销案)`;

      this.dialog.visible = true;
    },
    //确定
    async submit() {
      let param = {
        ...this.formline,
        allocAmount: this.total,
        allocPercent: this.showproportion,
        uninvoicedAmount: this.uninvoicedAmount,
      };
      if (this.showData.status == 2) {
        await casefinancial(param);
      } else {
        await purgecase(param);
      }

      console.log("提交成功");
      this.$emit("submit");
      this.$message.success("操作成功！");
      this.cancle();
    },
    cancle() {
      this.dialog.visible = false;
    },
    onadd(name, type) {
      this.formline[name].push({
        allocType: type,
        amount: "",
        description: "",
        percentage: "",
        remark: "",
      });
    },
    onaddlawyers() {
      this.$refs.userModal.open();
    },
  },
};
</script>

<style scoped lang="scss">
.close-dialog {
  display: flex;
  flex-direction: column;
  .foot {
    text-align: center;
    margin-top: 20px;
  }
  .row {
    display: flex;
  }
  .mar-10 {
    margin-top: 10px;
  }
  .col {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    span {
      display: inline-block;
      width: 120px;
      text-align: right;
    }
  }
  .w3 {
    width: 33%;
  }
  .w5 {
    width: 50%;
  }
  .w7 {
    width: calc(67% - 3px);
  }
}
::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
}
::v-deep .dev-form .el-form-item__error {
  bottom: -2px;
  top: auto;
  left: 10px;
}
::v-deep .dev-form .el-form-item__content {
  padding-bottom: 9px;
}
::v-deep .label {
  width: 120px;
}
::v-deep .el-input-number--medium {
  width: 177px;
}
::v-deep .el-input--medium .el-input__inner {
  height: 36px;
  line-height: 36px;
}
</style>
